package com.fw.kafka_chapter_1.quick.interceptor;

import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.LongAdder;

/**
 * @Author:yanwei
 * @Date: 2020/8/23 - 22:19
 */

public class ProducerInterceptorShould implements ProducerInterceptor<String,String> {

    private LongAdder longAdder = new LongAdder();


    /**
     * 实际消息处理
     * @param producerRecord
     * @return
     */
    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> producerRecord) {
        String value = producerRecord.value();

        return new ProducerRecord<>(producerRecord.topic(),producerRecord.key(),value.concat("- end"));
    }

    /**
     * 异常信息
     * @param recordMetadata
     * @param e
     */
    @Override
    public void onAcknowledgement(RecordMetadata recordMetadata, Exception e) {
        if (Objects.nonNull(e)) {
            // 失败发送
            longAdder.increment();
        }
    }

    /**
     * 拦截器结束
     */
    @Override
    public void close() {
        System.out.printf("失败数为\t\t%s\n",longAdder.sum());
    }

    /**
     * 空实现即可
     * @param map
     */
    @Override
    public void configure(Map<String, ?> map) {

    }
}
